<template>
  <!-- Desc：上传图片组件，专注3个地方：初始请求的回填、上传后的回调、提交时的拼接(个别特殊的别用此组件，反而更麻烦)；传单图时，有图片按钮隐藏，无图片按钮显示; 传多图时，按钮永远显示 -->
  <div
    :class="[
      'upload-container',
      imgSize,
      backfillList.length > 3 ? 'many' : '',
    ]"
  >
    <viewer :images="backfillList.map((item) => item.url)" class="upload-view">
      <div v-for="(item, index) in backfillList" :key="index" class="view-item">
        <a
          :href="item.filepath"
          :download="item.filepath"
          :target="
            item.filetype == 'jpg' || item.filetype == 'png'
              ? '' + '_blank'
              : '_self'
          "
          class="downLoad"
          >下载</a
        >
        <img
          :src="item.filepath"
          v-if="item.filetype == 'jpg' || item.filetype == 'png'"
        />
        <div v-else>
          <i class="iconfont icon-icon--"></i>
          <el-tooltip
            :content="item.filename ? item.filename : item.filepath"
            placement="bottom"
            effect="dark"
          >
            <p class="fileName">
              {{ item.filename ? item.filename : item.filepath }}
            </p>
          </el-tooltip>
        </div>
        <i class="el-icon-error" @click="imgDel(index)" />
      </div>
    </viewer>
    <!-- :on-remove="handleRemove" 被小红叉imgDl替代 -->
    <div
      class="upload-btn"
      :style="{
        display:
          String(backfillList) !== '' && limit === 1 ? 'none' : 'inline-block',
      }"
    >
      <el-upload
        v-if="backfillList.length !== limit"
        class="upload-demo"
        drag
        :limit="limit"
        multiple
        :action="uploadUrl"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        :on-error="handleError"
        :data="uploadData"
        :file-list="backfillList"
        :list-type="listType"
        :show-file-list="isShow"
      >
        <div class="btn">
          <i class="iconfont icon-shangchuan" />
          <p v-if="onlyImg">上传图片</p>
          <p v-else>上传文件</p>
        </div>
      </el-upload>
    </div>
  </div>
</template>

<script>
import { getQnToken } from '@/api/user'

export default {
  props: {
    filelist: {
      type: Array,
      default: () => [],
    },
    limit: {
      type: Number,
      default: 1,
    },
    listType: {
      type: String,
      default: 'picture-card',
    },
    isShow: {
      type: Boolean,
      default: true,
    },
    imgSize: {
      type: String,
      default: 'size148', // -版本(size148、size70、size36)
    },
    onlyImg: {
      default: false,
    },
  },
  watch: {
    filelist: {
      handler() {
        this.backfillList = JSON.parse(JSON.stringify(this.filelist))
      },
      deep: true, // 深度监听父组件传过来对象变化
    },
  },
  data() {
    return {
      uploadData: {
        token: '', // -七牛云凭证
        key: '', // -图片名处理
      },
      uploadUrl: 'https://upload-z2.qiniup.com', // -上传七牛云华南地区
      backfillList: [], // -接受父层回显、上传后list同步、删除同步、传给父层
    }
  },
  mounted() {
    this.getQnToken() // -加载组件就获取七牛云凭证
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    /**
     * 1. 获取七牛云(Token)
     */
    getQnToken: function() {
      getQnToken({}).then((res) => {
        res = res.data
        if (res) {
          localStorage.setItem('qToken', JSON.stringify(res.token))
          this.uploadData.token = res.token
        }
      })
    },
    /**
     * 2. 上传前：判断
     */
    beforeAvatarUpload(file) {
      const val = file.name
      var suffix = val.substring(val.lastIndexOf('.') + 1, val.length) // -拿到后缀，又把后缀拼回去
      // this.uploadData.key = new Date().format('yyyyMMdd') + file.uid + '.' + suffix // -图片改名成时间戳名不容易出BUG
      this.uploadData.key =
        '附件' + +new Date().format('yyyyMMddhhmmss') + '.' + suffix
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (this.onlyImg && !isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1024
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 1G!')
        return false
      }
    },
    /**
     * Init. 回填(加载)
     */
    init() {
      this.backfillList = JSON.parse(JSON.stringify(this.filelist))
    },
    /**
     * 3. 上传后：处理
     */
    handleAvatarSuccess(res, file, list) {
      this.backfillList = list.map((item) => {
        if (item.response) {
          // -新鲜的
          item.filename = item.response.key
          item.filepath = this.$QNIMAGE + item.response.key
          item.filetype = item.filepath.substring(
            item.filepath.lastIndexOf('.') + 1,
            item.filepath.length
          )
        } else {
          // -初始的
          item.filename = item.name.substring(
            item.name.lastIndexOf('/') + 1,
            item.name.length
          )
          item.filepath = item.name
          item.filetype = item.filepath.substring(
            item.filepath.lastIndexOf('.') + 1,
            item.filepath.length
          )
        }
        return item
      })
      this.$emit('backList', this.backfillList)
    },
    /**
     * 事件：用户删图
     */
    imgDel(index) {
      this.backfillList.splice(index, 1)
      this.$emit('backList', this.backfillList)
    },

    /**
     * 事件：上传报错
     */
    handleError: function(res) {
      alert(res)
    },
  },
}
</script>
<style lang="scss" scoped>
.upload-container {
  position: relative;
  display: inline-block;
  vertical-align: middle;
  /deep/.el-upload-dragger {
    width: 100%;
    height: 100%;
    border: 0;
  }
  /deep/.downLoad {
    position: absolute;
    top: 3px;
    left: 50%;
    transform: translateX(-50%);
    color: #fff;
    background: #ff6b72;
    border-radius: 6px;
    padding: 5px 8px;
    display: inline-block;
    font-size: 10px;
    line-height: 1;
  }
  /deep/ .el-upload {
    margin-right: 15px;
  }
  /* 左展示容器 */
  &.many .upload-view .view-item {
    margin: 0 15px 10px 0;
  } /* 单图或单图以下，无下边距，多图时(> 3)才出现下边距 */
  .upload-view {
    display: inline-block;
    vertical-align: top;
    .view-item {
      position: relative;
      display: inline-block;
      margin: 0 15px 0 0;
      vertical-align: top;
      box-shadow: 0 0 5px 3px #ecf0f1;
      img {
        width: 100%;
        height: 100%;
        cursor: pointer;
        border-radius: 5px;
      }
      i.el-icon-error {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 22px;
        color: #fe7676;
        cursor: pointer;
      }
    }
  }
  /* 右 UI 组件 */
  .upload-btn {
    display: inline-block;
    vertical-align: middle;
    .el-upload-list {
      display: none !important;
    } // 永久隐藏Element-UI组件的展示图部分
  }
}

/* 1. -148版 */
.upload-container.size148 {
  .upload-view .view-item {
    width: 148px;
    height: 148px;
  }
  /deep/ .upload-btn .el-upload.el-upload--picture-card {
    width: 148px;
    height: 148px;
    line-height: normal;
    color: #ff6b72;
  }
  /deep/ .upload-btn i {
    font-size: 34px;
    color: #ff6b72;
  }
}

/* 2. -100 版 */
.upload-container.size100 {
  .upload-view .view-item {
    width: 80px;
    height: 80px;
    padding: 10px;
    text-align: center;
    .iconfont {
      font-size: 50px;
      color: #ff6b72;
    }
    .fileName {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 10px;
      cursor: pointer;
    }
  }
  .btn {
    margin-top: 24.5px;
  }
  /deep/ .upload-btn .el-upload.el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: normal;
    color: #ff6b72;
    font-size: 10px;
    background: #fff;
    border-radius: 0;
    border: 1px dashed #737c8ab8;
  }
  /deep/ .upload-btn .el-upload.el-upload--picture-card:hover {
  }
  /deep/ .upload-btn i {
    font-size: 32px;
    color: #ff6b72;
  }
  //i.el-icon-error { top: -10px; right: -17px; font-size: 14px; }
  //&:hover i.el-icon-error { top: 0; right: -17px; z-index: 1; }
}

/* 2. -70 版 */
/* 2. -70 版 */
.upload-container.size70 {
  .upload-view .view-item {
    width: 50px;
    height: 50px;
    padding: 10px;
    text-align: center;
    .view_item_box {
      display: flex;
      justify-content: space-around;
      align-items: center;
      flex-direction: column;
      height: 100%;
    }
    .iconfont {
      font-size: 30px;
      color: #ff6b72;
    }
    .fileName {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 10px;
      cursor: pointer;
    }
  }
  .btn {
    margin-top: 15px;
  }
  /deep/ .upload-btn .el-upload.el-upload--picture-card {
    width: 70px;
    height: 70px;
    line-height: normal;
    color: #ff6b72;
    font-size: 10px;
    background: #fff;
    border-radius: 0;
    border: 1px dashed #737c8ab8;
  }
  /deep/ .upload-btn i {
    font-size: 24px;
    color: #ff6b72;
  }
}

/* 3. -36版 */
.upload-container.size36 {
  .upload-view .view-item {
    width: 36px;
    height: 36px;
    margin: 0;
    i.el-icon-error {
      top: -10px;
      right: -17px;
      font-size: 14px;
      z-index: -1;
    }
    &:hover i.el-icon-error {
      top: 0;
      right: -17px;
      z-index: 1;
    }
  }
  /deep/ .upload-btn .el-upload.el-upload--picture-card {
    width: 36px;
    height: 36px;
    line-height: normal;
    color: #ff6b72;
  }
  /deep/ .upload-btn i {
    font-size: 14px;
    color: #ff6b72;
  }
}
</style>
